package udpComunication;

import java.io.*;
import java.net.*;

public class MulticastServer {

	   //File da dove leggo, nella directory dove viene lanciato il server */
	   private static final String FILE = "/home/erond/Scrivania/RetiLS_project/sorgenti/l2capRtpAdapter_0.6/src/udpComunication/node_status.xml";
	   
	   private static BufferedReader in = null;
	   private static boolean moreLines = true;
	   static ByteArrayOutputStream boStream = null;
	   static DataOutputStream doStream = null;
	   static MulticastSocket socket = null;
	   static DatagramPacket packet = null;
	   static byte[] data = null;
	   
	   public static void main(String[] args)  {
	   long WAIT = 10000;
	   int port = -1;
	   // Indirizzo del gruppo multicast e porta
	   InetAddress group = null;
	   try
	   { if (args.length == 1)
	      { group = InetAddress. getByName("230.0.0.1");
	        port = Integer.parseInt(args[0]); }
	      else if (args.length == 2)
	       { group = InetAddress.getByName(args[0]);
	         port = Integer.parseInt(args[1]); }
	      else
	       { System.out.println("Usage: ..."); System.exit(1); }
	   }
	   catch (Exception e) {System.exit(1);}
	   
	   //	 Creazione datagram packet e socket
	   data = new byte[256];
	   packet = new DatagramPacket(data, data.length, group, port);
	   try {
	       socket = new MulticastSocket(port);
	       socket.joinGroup(group);
	         System.out.println("Socket: " + socket);
	   } catch (Exception e) { }
	   while (true)
	   { 
	     moreLines = true; // resetto indicatore linee
	     try {
             Thread.currentThread().sleep( WAIT );
        } catch (Exception e) { continue; }
	      try { 
	    	  // costruisco un nuovo buffered reader
	         in = new BufferedReader(new FileReader(FILE));
	       } catch (Exception e) { continue; }
	       while (moreLines) {
	        // estrazione della linea
	        String linea = LineUtility.getNextLine(in);
	        System.out.println("TEST: "+linea);
	         if (linea.equals("Nessuna linea disponibile")) { 
	        	 moreLines = false;
	        	 break; //esco dal ciclo
	        	 }
	          try
	          { 
	        	 boStream = new ByteArrayOutputStream();
	             doStream = new DataOutputStream(boStream);
	             doStream.writeUTF(linea);
	             data = boStream.toByteArray();
	             packet.setData(data);
	             socket.send(packet);
	           } catch (Exception e) {continue; }
	       	} 
	       } 
	   	}
}
